<template>
  <div class="patient-reception">
    <div class="left-panel-container">
      <div class="left-panel">
        <!-- 搜索条件 -->
        <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
          label-width="68px"
        >
          <el-form-item label="就诊卡号" prop="cardId">
            <el-input
              v-model="queryParams.cardId"
              placeholder="请输入就诊卡号"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="病人姓名" prop="patientName">
            <el-input
              v-model="queryParams.patientName"
              placeholder="请输入病人姓名"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
          <el-form-item label="科室" prop="departmentId">
            <el-select
              v-model="queryParams.departmentId"
              placeholder="请选择科室"
              clearable
            >
              <el-option
                v-for="dict in td_department"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="挂号状态" prop="status">
            <el-select
              v-model="queryParams.status"
              placeholder="请选择挂号状态"
              clearable
            >
              <el-option
                v-for="dict in register_status"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">
              搜索
            </el-button>
            <el-button icon="Refresh" @click="resetQuery"> 重置 </el-button>
          </el-form-item>
        </el-form>
        <!-- 聊天框按钮 -->
        <div class="chat-button-container" @click="toggleChat">
          <div class="chat-button"></div>
        </div>

        <!-- 挂号病人信息列表 -->
        <!-- 当数据为空时显示此部分 -->
        <div v-if="registerList.length === 0" class="no-data-placeholder">
          <i
            class="el-icon - circle - close"
            style="
              font-size: 60px;
              color: #ccc;
              display: block;
              margin: 0 auto 20px;
            "
          ></i>
          <p style="text-align: center; color: #666">暂无待就诊患者</p>
        </div>
        <!-- 当数据不为空时显示此部分 -->
        <div
          v-for="patient in registerList"
          :key="patient.id"
          class="patient-card-wrapper"
          @click="selectPatient(patient)"
        >
          <el-card
            class="patient-card"
            :class="{
              'visited-card': patient.status === 2,
              'unvisited-card': patient.status === 1,
            }"
          >
            <div class="patient-info">
              <!-- 性别图标显示 -->
              <div class="gender-department-container">
                <div class="gender-icon-container">
                  <el-icon v-if="patient.patientSex === '0'">
                    <Male />
                  </el-icon>
                  <el-icon v-if="patient.patientSex === '1'">
                    <Female />
                  </el-icon>
                </div>
                <div class="department-container">
                  <dict-tag
                    :options="td_department"
                    :value="patient.departmentId"
                  />
                </div>
              </div>
              <div class="info-item">就诊号: {{ patient.clinicId }}</div>
              <div class="info-item">就诊卡号: {{ patient.cardId }}</div>
              <div class="info-item">病人姓名: {{ patient.patientName }}</div>
              <div class="info-item">
                挂号时间 {{ formatDate(patient.createTime) }}
              </div>
            </div>
          </el-card>
        </div>
      </div>
    </div>
    <div class="right-panel">
      <div class="menu">
        <el-button type="primary" @click="showComponent('PatientInfo')"
          >病人信息</el-button
        >
        <el-button type="primary" @click="showComponent('medicalrecord')"
          >病历</el-button
        >
        <el-button type="primary" @click="showComponent('prescription')"
          >处方</el-button
        >
      </div>
      <div class="content">
        <component
          :is="currentComponent"
          :patient-id="selectedPatientId"
          :clinic-id="selectedClinicId"
        ></component>
      </div>
    </div>

    <!-- 聊天框 -->
    <div v-if="isChatOpen" class="chat-overlay">
      <ChatApp @close="toggleChat" />
    </div>
  </div>
</template>

<script setup name="Register">
import { listTodayRegister } from "@/api/clinic/register";
import { ref, reactive, toRefs, getCurrentInstance } from "vue";
// 引入 Element Plus 的性别图标
import { Male, Female } from "@element-plus/icons-vue";
import patientinfo from "../clinicinfo/patientinfo.vue";
import medicalrecord from "../clinicinfo/medicalrecord.vue";
import prescription from "../clinicinfo/prescription.vue";
import dayjs from "dayjs";
import ChatApp from "../../ai/chat/index.vue";
// import Prescription from './Prescription.vue'; // 引入处方组件
const { proxy } = getCurrentInstance();
const { td_department, register_status } = proxy.useDict(
  "time",
  "register_type",
  "td_department",
  "register_status"
);
const registerList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const total = ref(0);
const daterangeCreateTime = ref([]);
const startOfToday = new Date();
startOfToday.setHours(0, 0, 0, 0); // 设置为今天的开始时间（00:00:00）
const endOfToday = new Date();
endOfToday.setHours(23, 59, 59, 999); // 设置为今天的结束时间（23:59:59）
const data = reactive({
  form: {
    cardId: "",
    patientName: "",
    docterName: "",
    time: null,
    scheduleId: null,
  },
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    cardId: null,
    patientName: null,
    docterName: null,
    departmentId: null,
    departmentName: null,
    createTime: null,
    time: null,
    type: null,
    status: null,
    scheduleId: null,
  },
  schedulequeryParams: {
    pageNum: 1,
    pageSize: 10,
    departmentId: null,
    time: null,
    scheduleDate: new Date().toISOString().slice(0, 10), // 默认值为今天
    params: {}, // 添加 params 对象
  },
});

const { queryParams, form } = toRefs(data);
const currentComponent = ref(null); // 用于存储当前显示的组件
// 创建组件映射
const componentMap = {
  PatientInfo: patientinfo,
  medicalrecord: medicalrecord,
  prescription: prescription,
};

const selectedPatientId = ref(null); // 用于存储当前选中的病人 ID
const selectedClinicId = ref(null); // 用于存储当前选中的就诊 ID

const isChatOpen = ref(false); // 控制聊天框的显示和隐藏

// 切换聊天框的显示状态
const toggleChat = () => {
  isChatOpen.value = !isChatOpen.value;
};
// 格式化日期的函数
const formatDate = (date) => {
  if (!date) return "";
  return dayjs(date).format("YYYY-MM-DD");
};

function selectPatient(patient) {
  selectedPatientId.value = patient.patientId; // 设置当前选中的病人 ID
  selectedClinicId.value = patient.clinicId; // 设置当前选中的诊所 ID
  currentComponent.value = patientinfo; // 显示病人信息组件
}

// 定义 showComponent 方法
function showComponent(componentName) {
  currentComponent.value = componentMap[componentName];
  if (componentName === "medicalrecord" || componentName === "prescription") {
    // 确保 clinicId 被传递
    selectedClinicId.value = selectedClinicId.value;
  }
}

/** 查询挂号列表 */
function getList() {
  loading.value = true;
  queryParams.value.params = {};
  if (null != daterangeCreateTime && "" != daterangeCreateTime) {
    queryParams.value.params["beginCreateTime"] = daterangeCreateTime.value[0];
    queryParams.value.params["endCreateTime"] = daterangeCreateTime.value[1];
  }
  listTodayRegister(queryParams.value).then((response) => {
    registerList.value = response.rows;
    total.value = response.total;
    loading.value = false;
  });
}

// 取消按钮
function cancel() {
  open.value = false;
  reset();
}

// 表单重置
function reset() {
  form.value = {
    registerId: null,
    cardId: null,
    patientId: null,
    patientName: null,
    docterId: null,
    docterName: null,
    departmentId: null,
    departmentName: null,
    scheduleId: null,
    createTime: null,
    time: null,
    type: null,
    status: null,
  };
  proxy.resetForm("registerRef");
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  daterangeCreateTime.value = [];
  proxy.resetForm("queryRef");
  handleQuery();
}

getList();
</script>

<style scoped>
.patient-reception {
  display: flex;
  height: 100vh;
}
.left-panel-container {
  height: 100vh;
  overflow-y: auto;
  width: 230px;
}
.left-panel {
  border-right: 1px solid #ccc;
  padding: 2px;
  height: 100vh;
}
.right-panel {
  flex: 2;
  display: flex;
  flex-direction: column;
}
.menu {
  border-bottom: 1px solid #ccc;
  padding: 10px;
}
.content {
  flex: 1;
  padding: 5px;
}
.patient-card-wrapper {
  margin-bottom: 3px;
}
.patient-card {
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  border-radius: 4px;
  padding: 5px;
  width: 100%;
  max-width: 200px;
}
.visited-card {
  background-color: rgba(0, 128, 0, 0.3);
}
.unvisited-card {
  background-color: rgba(4, 101, 186, 0.635);
}
.patient-info {
  display: flex;
  flex-direction: column;
}
.info-item {
  margin-bottom: 3px;
  font-size: 14px;
  color: #333;
}
/* 搜索条件样式调整 */
.el-form {
  display: block;
}

.el-form-item {
  width: 200px;
  margin-bottom: 4px;
}

.el-input__inner,
.el-select__inner {
  width: 100%;
}

.el-form-item__content {
  width: 100%;
}

.gender-department-container {
  display: flex;
  align-items: center;
}

.gender-icon-container {
  margin-right: 50px;
}

/* 悬浮按钮样式 */
.chat-button-container {
  position: fixed;
  top: 80px; /* 距离顶部的距离 */
  right: 100px; /* 距离右侧的距离，稍微靠左 */
  z-index: 1000;
  cursor: pointer;
}

/* 聊天框样式 */
.chat-overlay {
  position: fixed;
  top: 0;
  right: 0;
  width: 700px; /* 聊天框的宽度 */
  height: 100%;
  background-color: rgba(255, 255, 255, 0.95);
  z-index: 1001;
  box-shadow: -2px 0 10px rgba(0, 0, 0, 0.2);
  transition: transform 0.3s ease;
}

/* 聊天框的进入和离开动画 */
.chat-overlay-enter-from,
.chat-overlay-leave-to {
  transform: translateX(100%);
}

.chat-overlay-enter-to,
.chat-overlay-leave-from {
  transform: translateX(0);
}

.chat-button {
  width: 140px; /* 按钮宽度 */
  height: 140px; /* 按钮高度 */
  background-image: url("/src/assets/images/ailogo.jpg"); /* 替换为你的图片路径 */
  background-size: contain; /* 确保图片完整显示 */
  background-position: center;
  background-repeat: no-repeat;
  border-radius: 50%; /* 如果需要圆形按钮 */
  border: 1px solid #409eff; /* 添加边框，可选 */
  display: flex;
  align-items: center;
  justify-content: center;
}
</style>
